package com.xsomnus.java_basic.bitops;

import java.util.Iterator;
import java.util.SortedSet;

/**
 * @author 叶小夏
 * @since 2019-08-23 15:48
 */
public class IntProtocol {

    private SortedSet<SegmentDefinition> parts;

    private int initVal = 0xff;

    private static final int COUNTS = 1 << 5;

    public IntProtocol(SortedSet<SegmentDefinition> parts) {
        if (parts.stream().mapToInt(SegmentDefinition::getBitCounts).sum() != COUNTS) {
            throw new IllegalArgumentException("total bit counts must be equal " + COUNTS);
        }
        this.parts = parts;
    }


    public int getVal() {
        int partLength = parts.size();
        if (partLength == 1) {
            return parts.first().getVal();
        }
        Iterator<SegmentDefinition> iterator = parts.iterator();
        int ret = 0;
        int currentShiftCounts = 0;
        while (iterator.hasNext()) {
            SegmentDefinition next = iterator.next();
            ret = ret | next.getVal() << currentShiftCounts;
            currentShiftCounts = currentShiftCounts + next.getBitCounts();
        }
        return ret;

    }

}
